import { makeAutoObservable, observable } from 'mobx';
import * as api from './api';

export default class ManagersStore {
  _args = {
    search: {
    },
    pg: {
      page: 0,
      sort: ['accountManagerInfo.registerTime;desc'],
      size: 10,
    },
  };
  _args_relate = {
    search: {
    },
    pg: {
      page: 0,
      sort: ['crDate;desc'],
      size: 10,
    },
  };
  total = 0;
  data = [];
  loading = false;

  relate_total = 0;
  relate_data = [];
  relate_loading = false;

  from = '';
  to = '';

  constructor(rootStore) {
    this.rootStore = rootStore;
    makeAutoObservable(this, { rootStore: false });
  }

  /**
   * 使用设置的请求参数和分页配置请求列表数据
   * 分页参数为空时保持当前分页配置
   * @param {object} pgInfo 分页参数
   */
  * query(pgInfo) {
    _.mergeWith(this._args.pg, pgInfo, (o, s) => (_.isArray(o) ? s : undefined)); // 数组直接赋值，不合并
    const { search, pg } = toJS(this._args);
    const { orderDate = [] } = search;
    const [from, to] = orderDate;
    this.from = from;
    this.to = to;
    search.userTypes = [4];
    // if (!pg.sort?.length) delete pg.sort;
    this.loading = true;
    try {
      this.total = yield api.count({ search });
      const res = yield api.get({ search, pg });
      this.data = yield Promise.all(res.map(async (p) => {
        const orderCommissionTotal = await api.getExcelsStatistics({ username: p.id, type: '4', orderType: '0', search: { from, to } });
        return { ...p, orderCommissionTotal };
      }));
    } finally {
      this.loading = false;
    }
  }

  * query_relate(pgInfo) {
    _.mergeWith(this._args_relate.pg, pgInfo, (o, s) => (_.isArray(o) ? s : undefined)); // 数组直接赋值，不合并
    const { search, pg } = toJS(this._args_relate);
    search.receiving = false;
    // if (!pg.sort?.length) delete pg.sort;
    this.relate_loading = true;
    try {
      this.relate_total = yield api.getManagersInfoCount({ search });
      this.relate_data = yield api.getManagersInfo({ search, pg });
    } finally {
      this.relate_loading = false;
    }
  }

  * get(args) {
    const res = yield api.getCustomerUser(args);
    return observable(res);
  }

  * create(data, args) {
    yield api.create(data, args);
    yield this.query();
  }

  * remove(data) {
    yield api.remove(data);
    yield this.query();
  }

  * update(data) {
    yield api.update({ ...data, status: data.status ? 1 : 0 });
    yield this.query();
  }

  * getInetusersMobile(args) {
    return yield api.getInetusersMobile(args);
  }

  * updateStatus(data) {
    const partner = {};
    partner.partnerInfo = data.partnerInfo;
    partner.partnerInfo.partnerStatus =
      partner.partnerInfo.partnerStatus === 1 ? 0 : 1;
    yield api.updateStatus(data.username, partner);
    yield this.query();
  }

  * addProfitShare(args) {
    const { username, accountManagerInfo } = args;
    const { baseUrl, imgUrl, mpAppId } = global.getEnvCfg();
    const userInfo = yield api.addProfitShare('MANAGER', username, accountManagerInfo?.independentAccount?.period || '1');
    const text = encodeURIComponent(`${imgUrl}/mp/?appId=${mpAppId}&sid=${userInfo.sid}`);
    const url = `${baseUrl}/api/files/qrcode?text=${text}&height=300&width=300`;
    return url;
  }

  async getDictsItems(id) {
    try {
      const res = await api.getDictsItems(id);
      const data = {};
      for (const item of res) {
        data[item.itemId] = item.name;
      }
      return data;
    } catch (error) {
      console.log('🚀 _ file: PartnerStore.js:151 _ PartnerStore _ error:', error);
    }
  }

  * getManagersInfo(search) {
    return yield api.getManagersInfo(search);
  }

  * getManagersInfoCount(search) {
    return yield api.getManagersInfoCount(search);
  }

  idx(i) {
    return this._args.pg.page * this._args.pg.size + i + 1;
  }

  idx_relate(i) {
    return this._args_relate.pg.page * this._args_relate.pg.size + i + 1;
  }

  get pg() {
    return this._args.pg;
  }

  set pg(pg) {
    this.query({ ...pg });
  }

  get pg_relate() {
    return this._args_relate.pg;
  }

  set pg_relate(pg) {
    this.query_relate({ ...pg });
  }

  get api() {
    return api;
  }

  get orderStatus() {
    return this._orderStatus;
  }

  set orderStatus(value) {
    this._orderStatus = value;
    this._args.pg.page = 0;
    this.query({ page: 0 });
  }

  get search() {
    this._args.pg.page = 0;
    return this._args.search;
  }

  set search(search) {
    this._args.pg.page = 0;
    this._args.search = search;
    this.query({ page: 0 });
  }

  get search_relate() {
    this._args_relate.pg.page = 0;
    return this._args.search;
  }

  set search_relate(search) {
    this._args_relate.pg.page = 0;
    this._args_relate.search = search;
    this.query_relate({ page: 0 });
  }

  get tableSort() {
    if (this._args.pg.sort?.length) {
      const [fn, dir] = this._args.pg.sort[0].split(';');
      return { [fn]: dir };
    }
    return undefined;
  }
}
